﻿using System;
using System.Web.Mvc;
using ProjetoComperio.Framework.Web.Mail;

namespace ProjetoComperio.Framework.Web.Logging
{
    public class ExceptionLoggingAttribute : ActionFilterAttribute, IActionFilter
    {
        //  private static LoggerDataStoreEntities DataStore = new LoggerDataStoreEntities();
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {

            if (filterContext.Exception != null)
            {
                ExceptionLogging exception = new ExceptionLogging();
                exception.Date = DateTime.Now;
                exception.Message = filterContext.Exception.Message;
                exception.Source = filterContext.Exception.Source;
                exception.StackTrace = filterContext.Exception.StackTrace;
                exception.TargetSite = filterContext.Exception.TargetSite.ToString();
                exception.URL = filterContext.HttpContext.Request.Url.ToString();
                exception.UserAgent = filterContext.HttpContext.Request.UserAgent;
                exception.UserName = filterContext.HttpContext.User.Identity.Name;
                Logging.Logger.StoreException(exception);
                MailSender.SendMail("Higor.crr@gmail.com", "Ocorreu uma exceção no sistema", filterContext.Exception.GetFullDescription());
                MailSender.SendMail("equipe@projetocomperio", "Ocorreu uma exceção no sistema", filterContext.Exception.GetFullDescription());
                filterContext.HttpContext.ClearError();
                filterContext.HttpContext.Response.Redirect("/Home/Error");
            }
        }

    }
}
